﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace WoChu.CF.BaseFrame.Util
{
    /// <summary>
    /// 本地INI 文件读写。
    /// </summary>
    public class IniFile
    {
        public static readonly string PRINT_INI_FILE_PATH = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase) + @"/GFPDASetting.ini";
        private string _IniFilePath;

        public string Path
        {
            get { return _IniFilePath; }
            set { _IniFilePath = value; }
        }
        /// <summary>
        /// 
        /// </summary>
        public IniFile()
        {
            _IniFilePath = PRINT_INI_FILE_PATH;
        }
        /// <summary>
        /// 构造函数....
        /// </summary>
        /// <param name="INIPath"></param>
        public IniFile(string iniFilePath)
        {
            _IniFilePath = iniFilePath;
        }
        /// <summary>
        /// 写数据...
        /// </summary>
        /// <param name="Section"></param>
        /// <param name="Key"></param>
        /// <param name="Value"></param>
        public void WriteValue(string section, string sKey, string sValue)
        {
            writePrivateProfileString(section, sKey, sValue, this._IniFilePath);
        }
        /// <summary>
        /// 读数据...
        /// </summary>
        /// <param name="Section"></param>
        /// <param name="Key"></param>
        /// <returns></returns>
        public string ReadValue(string sSection, string sKey)
        {
            return getPrivateProfileString(sSection, sKey, "", this._IniFilePath);
        }

        #region 寫入信息文件
        private void writePrivateProfileString(string sApplicationName, string sKeyName, string sValue, string FileName)
        {
            string[] iniItems = new string[0];
            string iniLines = null;
            string iniLine = null;
            string iniItem = null;
            int i, j;
            try
            {
                //读取INI文件；
                System.IO.StreamReader iniFile = new System.IO.StreamReader(FileName, System.Text.Encoding.Default);
                iniLines = iniFile.ReadToEnd();
                iniFile.Close();
            }
            catch
            {
            }
            //如果信息文件还沒有任何內容，就将节点到第一行 覆盖
            if (iniLines == null)
            {
                StreamWriter creatFile = File.CreateText(FileName);
                creatFile.Close();
                StreamWriter fileWriter = new StreamWriter(FileName, true, System.Text.Encoding.Default);
                fileWriter.WriteLine("[" + sApplicationName + "]");
                fileWriter.WriteLine(sKeyName + "=" + sValue);
                fileWriter.Close();
                return;
            }
            else
            {
                //否则的话得到已有的节点
                iniItems = System.Text.RegularExpressions.Regex.Split(iniLines, "\r\n");
            }
            //以回车符分割,得到每一行
            bool haveParentNode = false;
            string iniContent = "";
            int indexLength = 0;
            if (iniItems[iniItems.Length - 1] == "")
            {
                indexLength = iniItems.Length - 1;
            }
            else
            {
                indexLength = iniItems.Length;
            }
            for (i = 0; i < indexLength; i++)
            {
                iniItem = iniItems[i].Trim();
                if (iniItem[0] != '[' || iniItem[iniItem.Length - 1] != ']')
                    continue;

                if (iniContent == "")
                {
                    iniContent = iniItems[i].ToString();
                }
                else
                {
                    iniContent += "\r\n" + iniItems[i].ToString();
                }
                if (iniItems[i].ToString() == "[" + sApplicationName + "]")
                {
                    haveParentNode = true;
                    bool existsNode = false;
                    try
                    {
                        //找到相对应的父节点的話，查找是否有对应的子节点
                        for (j = (i + 1); j < indexLength; j++)
                        {
                            iniLine = iniItems[j].Trim();
                            if (iniLine[0] == '[' && iniLine[iniLine.Length - 1] == ']')
                            {
                                if (!existsNode)
                                {
                                    existsNode = true;
                                    iniContent += "\r\n" + sKeyName + "=" + sValue;
                                }
                                break;
                            }
                            iniLine = iniItems[j].TrimStart().Replace("   ", "");
                            if (iniLine.Substring(0, Math.Min(sKeyName.Length + 1, iniLine.Length)).ToUpper() == sKeyName.ToUpper() + "=")
                            {
                                //如果找到了Key匹配
                                existsNode = true;
                                iniContent += "\r\n" + sKeyName + "=" + sValue;
                            }
                            else
                            {
                                iniContent += "\r\n" + iniItems[j].ToString();
                            }
                        }
                    }
                    catch (System.Exception ex) { ex.ToString(); }
                    if (!existsNode)
                    {
                        existsNode = true;
                        iniContent += "\r\n" + sKeyName + "=" + sValue;
                    }
                }
                else
                {
                    for (j = (i + 1); j < indexLength; j++)
                    {
                        iniLine = iniItems[j].Trim();
                        if (iniLine[0] == '[' && iniLine[iniLine.Length - 1] == ']')
                        {
                            break;
                        }
                        else
                        {
                            iniContent += "\r\n" + iniItems[j].ToString();
                        }
                    }
                }
            }
            if (!haveParentNode)
            {
                iniContent += "\r\n[" + sApplicationName + "]";
                iniContent += "\r\n" + sKeyName + "=" + sValue;
            }
            StreamWriter replaceFile = File.CreateText(FileName);
            replaceFile.Close();
            StreamWriter replaceWriter = new StreamWriter(FileName, true, System.Text.Encoding.Default);
            replaceWriter.Write(iniContent);
            replaceWriter.Close();
        }
        #endregion

        #region 读取信息文件
        private string getPrivateProfileString(string sApplicationName, string sKeyName, string sDefault, string sFileName)
        {
            string[] iniItems = new string[0];
            string iniLines;
            string iniLine;
            int i, j;
            try
            {
                //读取INI文件；
                System.IO.StreamReader iniFile = new System.IO.StreamReader(sFileName, System.Text.Encoding.Default);
                iniLines = iniFile.ReadToEnd();
                iniFile.Close();
            }
            catch
            {
                return sDefault;
            }
            //以回车符分割,得到每一行
            iniItems = System.Text.RegularExpressions.Regex.Split(iniLines, "\r\n");
            //遍历每一行
            for (i = 0; i < iniItems.GetLength(0); i++)
            {
                //找到匹配值
                if (iniItems[i].Trim().ToUpper() != '[' + sApplicationName.Trim().ToUpper() + ']')
                    continue;

                //从下一行开始搜索
                for (j = i + 1; j < iniItems.GetLength(0); j++)
                {
                    iniLine = iniItems[j].Trim();
                    if (iniLine.Length > 0)
                    {
                        //如果找到了另一个段，那么就越段了，则返回默认值得
                        if (iniLine[0] == '[' && iniLine[iniLine.Length - 1] == ']')
                            return sDefault;
                    }
                    //去掉所有空格
                    iniLine = iniItems[j].TrimStart().Replace("   ", "");
                    if (iniLine.Substring(0, Math.Min(sKeyName.Length + 1, iniLine.Length)).ToUpper() == sKeyName.ToUpper() + "=")
                    {
                        //如果找到了Key匹配
                        return iniItems[j].Substring(iniItems[j].IndexOf('=') + 1);
                    }
                }
                return sDefault; //没有找到key匹配的，则返回默认值

            }
            return sDefault; //返回默认值
        }
        #endregion

    }
}
